<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"/>
    <title>组件的mixin</title>
</head>
<body>
<div id="app"></div>

<!--script-->
<script src="lib/react/react.js"></script>
<script src="lib/react/JSXTransformer.js"></script>
<script type="text/jsx">
    var stateRecordMixin = {
        componentWillMount: function () {
            this.oldState = []
        },
        componentWillUpdate: function (nextProps, nextState) {
            this.oldState.push(nextState);
        },
        previousState: function () {
            var index = this.oldState.length - 1;
            return index == -1 ? {} : this.oldState[index];
        }
    };
    var MessageBox = React.createClass({
        mixins: [stateRecordMixin],
        getInitialState: function () {
            console.log('getInitialState')
            return {
                count: 0
            }
        },
        doUpdate: function () {
            this.setState({
                count: this.state.count + 1
            });
            alert('上一次的计数:' + this.previousState().count);
        },
        render: function () {
            console.log("render");
            return (
                <div>
                    <h1>计数:{this.state.count}</h1>
                    <button onClick={this.killMyself}>卸载掉这个组件</button>
                    <button onClick={this.doUpdate}>手动更新一下</button>
                    <SubMessage count={this.state.count}/>
                </div>
            );
        }
    });

    var SubMessage = React.createClass({
        mixins: [stateRecordMixin],
        getInitialState: function () {
            return {
                count: 0
            }
        },
        componentWillReceiveProps: function (nextProps) {
            this.setState({
                count: this.props.count * 2
            });
        },
        render: function () {
            console.log('上一次子组件的计数:' + this.previousState().count);
            return (
                <div>
                    <h3>当前子组件的计数是:{this.state.count}</h3>
                </div>
            )
        }
    });

    var messageBox = React.render(<MessageBox/>,
        document.getElementById("app")
    );
</script>
</body>
</html>
